<?php
// author AliceXT
class CouponModel extends Model {

	public $coupon_id;
	public $Coupon;
	
	function _initialize(){
		parent::_initialize('Coupon');
	}
	
	
	public function _list($map,$sort='sort',$pagesize=20){
		$db = M('Coupon_sn');
		//计算总页数
		$count=$db->where($map)->count();
		//实例化分页类
		import ( 'ORG.Util.Page' );
		$p=new Page($count,$pagesize);
		$list = $db->where($map)->order($sort)->limit($p->firstRow.',
'.$p->listRows)->select();
        $pages=$p->show();
		$data['list']=$list;
		$data['pages']=$pages;
		return $data;
	}
	
	
	

	/**
	*参数num:新的个数，$id:优惠券ID
	*校对Sn码
	*如果sn数量比设置的值多，则返回false
	*如果sn数量比设置的值少，则增加相应的sn码并返回true
	*如果sn数量和原来的一样多，则返回true
	**/
	public function adjustSn($num,$id){
		if(empty($id)){
			$this->error = "没有该优惠券";
			return false;
		}else{
			$count = $this->countSn($id);
			// dump($count."-".$num);
			// dump("进入有ID");
			// 数量比设置的值少
			if($count < $num){
				// 增加少了的sn码
				$this->addSn($num - $count,$id);
				return true;
			}else{
				if($count > $num){
					$this->error = "不能设置比原来少的优惠券票数";
					return false;
				}else{
					return true;
				}
			}
		}
		return true;
	}

	// 重写create方法，加入adjustSn函数
	// public function create($data='',$type=''){
	// 	$data = $data ? $data : $_POST;
		
	// 	$adjustSn = $this->adjustSn($data['num'],$data['id']);

	// 	if($adjustSn){
	// 		return parent::create($data,$type);
	// 	}else{
	// 		return $adjustSn;
	// 	}
	// }

	// 计算sn码数量
	public function countSn($id){
		$Sn = M('coupon_sn');
		$map['coupon_id'] = $id;
		return $count = $Sn->where($map)->count();
	}
	// 根据输入的次数创建sn码
	public function addSn($times = 1,$id){
		$Sn = M('coupon_sn');
		$data['site_id'] = $this->site_id;
		$data['status'] = '1';
		$data['coupon_id'] = $id;
		for($i = 0;$i < $times;$i++){
			$data['sn'] = $sn = time().rand(1000000,9999999);
			// $data['ctime'] = time();
			$result[] = $Sn->add($data);
		}
	}
}